import { createI18n } from 'vue-i18n'
import messages from './messages'
import { AvailableLocales } from './types'

const i18n = createI18n({
  messages,
  locale: 'en',
  fallbackLocale: 'en',
  legacy: false, // 使用 Composition API 模式，则需要将其设置为false
  allowComposition: true, // you need to specify that!
  globalInjection: true, // 全局生效$t
})

export const changeLanguages = (lang: AvailableLocales) => {
  i18n.global.locale.value = lang
}

// 异步加载 views 功能模块下的语言包
const loadLocaleMessageForViewsFeatuer = () => {
  const langs = import.meta.glob('@/views/**/config/locales/*.json')
  Object.values(langs).forEach((value) => {
    const config = value.name.match(
      /views\/(?<name>\w*)\/config\/locales\/(?<lang>\w*).json/
    )
    if (config?.groups) {
      const { lang, name } = config.groups
      value().then((json) => {
        i18n.global.mergeLocaleMessage(lang, { [name]: json })
      })
    }
  })
}
loadLocaleMessageForViewsFeatuer()

export default i18n
